package com.xiaoq.manager.endpoint;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.sites.IMerchantApi;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.manager.entity.MerchantFunEntity;
import com.xiaoq.manager.entity.MerchantMgrEntity;
import com.xiaoq.manager.entity.MerchantRoleEntity;
import com.xiaoq.manager.service.IManagerAccountService;
import com.xiaoq.manager.service.IMerchantFunService;
import com.xiaoq.manager.service.IMerchantRoleService;
import com.xiaoq.manager.vo.ManagerAccountVo;
import com.xiaoq.oauth2.entity.OAuth2TokenEntity;
import com.xiaoq.oauth2.service.OAuth2Service;
import com.xiaoq.users.redis.RedisTemplate4JedisCluster;

@RestController
@RequestMapping("/api/v1/user/qllogin")
@Api(tags={"扫码登录相关Api"})
public class QlLoginEndpoint {
	
	@Autowired
	private IdGenerator idGenerator;
	
	private class ManagerAccountDataResponse extends GenericDataResponse<ManagerAccountVo> {}
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;
	
	@Autowired
	private IManagerAccountService managerAccountSer;
	
	@Autowired
	private OAuth2Service oAuth2Service;
	
	@Autowired
	private IMerchantFunService merchantFunSer;
	
	@Autowired
	private IMerchantRoleService merchantRoleSer;
	
	@Reference(interfaceClass=IMerchantApi.class,check=false,version="1.0.0")
	private IMerchantApi merchantDubboApi;
	
	public final static class QlCodeResponse extends GenericDataResponse<String>{}
	public final static class LoginSuccessResponse extends GenericDataResponse<String>{}
	
	private Logger logger = LoggerFactory.getLogger(QlLoginEndpoint.class);
	
	/**
	 * 二维码地址是http://localhost:9701/api/v1/user/qllogin
	 * @param response
	 * @return
	 */
	@ApiOperation(value="获取二维码url", notes="点击超链接返回更具url返回一个二维码")
	@GetMapping(value="")
	public void getQlCode(HttpServletResponse response){
		
		String unitId = idGenerator.nextId();
		redisTemplate.setWithExpireTime("qlcode", unitId,"smallCode",1800);
		BufferedImage imag = QlCodeUtil.zxingCodeCreate(unitId, 300, 300, "jpg");
		if(imag!=null){
		response.setHeader("Pragma", "no-cache");        
		response.setHeader("Cache-Control", "no-cache");        
		response.setDateHeader("Expires", 0);        
		response.setContentType("image/jpeg"); 
		try {
			ServletOutputStream sos = response.getOutputStream();
			ImageIO.write(imag, "jpeg", sos);
			sos.flush();
		} catch (IOException e) {
			logger.error("二维码输出流出错", e);
		}
		}else{
			logger.info("BufferedImage 为空报空指针异常！");
		}
	}
	
	
	
	/**
	 * 
	 * @param qlUid
	 * @return  返回Unitcode 则登录成功, 返回为空则继续刷新, 返回9999则刷新二维码
	 * 
	 */
	@ApiOperation(value="ajax轮询查看是否登录成功",notes="ajax轮询查看登录状态")
	@ApiResponses({
		@ApiResponse(code=200, response= ManagerAccountDataResponse.class,message = "获取服务器端二维码的登录状态！")
	})
	@GetMapping(value="/status", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> isSuccess(
			@RequestParam(value = "qlUid", required = true) @ApiParam(value = "qlUid", required = true) String qlUid) {
		// 判断二位码是否过期
		String userId = redisTemplate.get("qlcode", qlUid);
		// 这里的userId 其实指的是管理员Id
		if (userId != null) {
			if (!userId.equals("smallCode")) {
				MerchantMgrEntity merchantMgrInDB = managerAccountSer.findById(userId);
				HttpHeaders httpHeaders = setToken4HttpHeadersByDays(String.valueOf(merchantMgrInDB.getId()), 3);
				ManagerAccountVo managerAccVo = new ManagerAccountVo();
				BeanUtils.copyProperties(merchantMgrInDB, managerAccVo);

				String merchantId = merchantMgrInDB.getMerchantId();
				String merchantStatus = merchantDubboApi.getMerchantStatus(merchantId);
				if (StringUtils.isEmpty(merchantStatus)) {
					merchantStatus = "000";
				}
				managerAccVo.setMerchantStatus(merchantStatus);
				return ManagerAccountDataResponse.okWithData(managerAccVo, httpHeaders);// 成功应该返回一个Token和用户的详细信息
				// 返回的user信息(accessToken)吧,不成功为空吧
			} else {
				return LoginSuccessResponse.okWithData("");
			}
		} else {
			return LoginSuccessResponse.ng("二维码过期请刷新！");
		}

	}
	
	
	/**
	 * 
	 * @param accessToken  用户登录授权的id
	 * @param qlUid  移动端扫描得到的id
	 * @return
	 */
	@ApiOperation(value="移动端确定登录",notes="移动端确定登录")
	@ApiResponses({
		@ApiResponse(code=200, response= GenericResponse.class,message = "移动端确定登录！")
	})
	@PostMapping(value="/{userId}/ensure", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> conLogin(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId, @RequestParam(value="qlUid",required=true)String qlUid){
		
		String qlKey = redisTemplate.get("qlcode",qlUid);
		if(qlKey!=null){
			redisTemplate.setWithExpireTime("qlcode",qlUid,userId,1000);
			logger.debug(redisTemplate.get("qlcode",qlUid));
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("二位码过期请刷新二维码！");
		}
		
		
		
		
	}
	
	private HttpHeaders setToken4HttpHeadersByDays(String userId,int durToken) {
		// 为用户生成access_token与refresh_token,手机端进行缓存,进入信息完善页面时,可以利用access_token与refresh_token进行用户信息更新
		OAuth2TokenEntity oAuth2Token = oAuth2Service.getAccessTokenAndRefreshToken4XiaoqAPP(userId,
				"lifestyle365-secret-201611120-20191119", durToken);
		String bearerAccessToken = "Bearer " + oAuth2Token.getAccessToken();
		String refreshToken = oAuth2Token.getRefreshToken();

		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.set("access_token", bearerAccessToken);
		httpHeaders.set("refresh_token", refreshToken);

		logger.info("bearer access_token : " + bearerAccessToken);
		logger.info("refresh_token : " + refreshToken);
		return httpHeaders;
	}
	

}
